package com.xin.minibusmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xin.minibusmall.product.dao.BrandDao;
import com.xin.minibusmall.product.dao.CategoryBrandRelationDao;
import com.xin.minibusmall.product.service.CategoryBrandRelationService;
import com.xin.minibusmall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xin.common.utils.PageUtils;
import com.xin.common.utils.Query;

import com.xin.minibusmall.product.dao.CategoryDao;
import com.xin.minibusmall.product.entity.CategoryEntity;
import com.xin.minibusmall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redis;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2树形结构分类
        // 1)过滤出所有的一级分类
        List<CategoryEntity> entitiesTree = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                })
                .sorted(Comparator.comparing(CategoryEntity::getSort))
                .collect(Collectors.toList());

        return entitiesTree;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = findParentDfs(catelogId, new ArrayList<>());
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size() - 1]);
    }

    @Override
    public List<Long> findParentDfs(Long catelogId, List<Long> path) {
        path.add(catelogId);
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentDfs(categoryEntity.getParentCid(), path);
        }
        return path;
    }

    @Override
    public void updateCascade(CategoryEntity category) {
        this.baseMapper.updateById(category);
        // 更新其他表的冗余字段
        categoryBrandRelationService.updataCategory(category.getCatId(), category.getName());
        // 同时修改缓存的数据
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }

    //先从redis查，没有在从数据库查
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        String catalogJSON = redis.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> catalogJsonFromDB = getCatalogJsonFromDBWithLocalLock();
            redis.opsForValue().set("catalogJSON", JSON.toJSONString(catalogJsonFromDB), 1, TimeUnit.DAYS);
            return catalogJsonFromDB;
        }
        return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
    }

    // 使用redisson分布锁，获取三级分类（当缓存不存在数据，则限制一个线程去数据库查，查完便更新到redis，其他线程则在redis获取）
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedissonLock() {
        
    }

    // 从数据库中获取三级分类的数据
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDB() {
        //  先一次性查出所有分类
        List<CategoryEntity> allCategorys = baseMapper.selectList(null);

        // 1.查出所有1级分类
        List<CategoryEntity> level1Categorys = getLevel1Categorys();
        // 2.封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 1.每个1级分类，查到这个分类的所有二级分类
            List<CategoryEntity> entities = getParent_cid(allCategorys, v.getCatId());
            // 2.封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (entities != null) {
                catelog2Vos = entities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 1.找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(allCategorys, l2.getCatId());
                    if (level3Catelog != null) {
                        // 2.封装成指定格式
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        // 3.放入缓存
        redis.opsForValue().set("catalogJSON", JSON.toJSONString(parent_cid), 1, TimeUnit.DAYS);

        return parent_cid;

    }

    //从数据库中获取数据,采用redis的本地锁（不适用分布式）
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithLocalLock() {

        synchronized (this) {
            // 上锁，先查询缓存
            String catalogJSON = redis.opsForValue().get("catalogJSON");
            if (!StringUtils.isEmpty(catalogJSON)) {
                return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                });
            }

            //  先一次性查出所有分类
            List<CategoryEntity> allCategorys = baseMapper.selectList(null);

            // 1.查出所有1级分类
            List<CategoryEntity> level1Categorys = getLevel1Categorys();
            // 2.封装数据
            Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                // 1.每个1级分类，查到这个分类的所有二级分类
                List<CategoryEntity> entities = getParent_cid(allCategorys, v.getCatId());
                // 2.封装上面的结果
                List<Catelog2Vo> catelog2Vos = null;
                if (entities != null) {
                    catelog2Vos = entities.stream().map(l2 -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                        // 1.找当前二级分类的三级分类封装成vo
                        List<CategoryEntity> level3Catelog = getParent_cid(allCategorys, l2.getCatId());
                        if (level3Catelog != null) {
                            // 2.封装成指定格式
                            List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                                Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                                return catelog3Vo;
                            }).collect(Collectors.toList());
                            catelog2Vo.setCatalog3List(collect);
                        }
                        return catelog2Vo;
                    }).collect(Collectors.toList());
                }
                return catelog2Vos;
            }));
            // 3.放入缓存
            redis.opsForValue().set("catalogJSON", JSON.toJSONString(parent_cid), 1, TimeUnit.DAYS);

            return parent_cid;
        }
    }

    //根据id查询出此id的所有下一级分类
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> list, Long parent_cid) {
        return list.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
    }

    //递归查询所有子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                .collect(Collectors.toList());
        return children;

    }
}